package com.gs.synedocket.fragment;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.gs.synedocket.R;
import com.gs.synedocket.activity.DocketActivity;
import com.gs.synedocket.activity.ImagePreviewActivity;
import com.gs.synedocket.apiresult.ApiResultData;
import com.gs.synedocket.constant.AllConstants;
import com.gs.synedocket.constant.EventCode;
import com.gs.synedocket.db.bean.Event;
import com.gs.synedocket.db.dao.LogUtil;
import com.gs.synedocket.db.dto.ScanPaperDto;
import com.gs.synedocket.dialog.ComboPicDialog;
import com.gs.synedocket.dialog.CommDialogUtils;
import com.gs.synedocket.dialog.LoadingDialogUtils;
import com.gs.synedocket.dialog.ToastDialogUtils;
import com.gs.synedocket.fragment.base.BaseFragment;
import com.gs.synedocket.presenter.ScanPaperPresenter;
import com.gs.synedocket.util.AppUtil;
import com.gs.synedocket.util.DocketUtil;
import com.gs.synedocket.util.FileUtils;
import com.gs.synedocket.util.ImageUtil;
import com.gs.synedocket.util.OKHttpUtil;
import com.gs.synedocket.util.PermissionUtil;
import com.gs.synedocket.util.PhotoUtil;
import com.gs.synedocket.util.StringUtil;
import com.gs.synedocket.util.ToastUtil;
import com.gs.synedocket.view.IScanPaperView;
import com.uuzuche.lib_zxing.activity.CaptureActivity;
import com.uuzuche.lib_zxing.activity.CodeUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;

public class ScanPaperFragment extends BaseFragment<IScanPaperView, ScanPaperPresenter> implements IScanPaperView {

    private RelativeLayout rlPhoto;
    private ImageView ivAddPhoto, ivPhoto;
    private String photo;
    private EditText etDocket;
    private ScanPaperDto mBean;
    private ActivityResultLauncher<Intent> activityResultLauncher;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_scan_paper;
    }

    @Override
    protected ScanPaperPresenter createPresenter() {
        return new ScanPaperPresenter();
    }

    @Override
    protected void initView() {
        initActivityResult();
        MyOnClickListener onClickListener = new MyOnClickListener();
        ivAddPhoto = fd(R.id.iv_add_photo);
        ivPhoto = fd(R.id.iv_photo);
        rlPhoto = fd(R.id.rl_photo);
        etDocket = fd(R.id.et_docket);
        ivPhoto.setOnClickListener(onClickListener);
        ivAddPhoto.setOnClickListener(onClickListener);
        fd(R.id.iv_scan).setOnClickListener(onClickListener);
        fd(R.id.iv_delete).setOnClickListener(onClickListener);
        fd(R.id.btn_confirm).setOnClickListener(onClickListener);
        fd(R.id.btn_submit).setOnClickListener(onClickListener);
    }

    private void initActivityResult() {
        activityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
            Intent data = result.getData();
            if (result.getResultCode() != 0 && data != null) {
                Bundle bundle = data.getExtras();
                if (bundle == null) {
                    return;
                }
                if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                    String docket = bundle.getString(CodeUtils.RESULT_STRING);
                    if (!TextUtils.isEmpty(docket)) {
                        LogUtil.getInstance().insertOrReplaceData("掃描二維碼結果：" + docket);
                        docket = docket.toLowerCase();
                        if (docket.contains("/r/n")) {
                            docket = docket.substring(0, docket.indexOf("/r/n"));
                        } else if (docket.contains("\\r\\n")) {
                            docket = docket.substring(0, docket.indexOf("\\r\\n"));
                        }
                        docket = docket.toUpperCase();
                        etDocket.setText(docket);
                    } else {
                        etDocket.setText("");
                    }
                }
            }
        });
    }

    @Override
    protected void initData() {

    }

    @Override
    public void onUploadFileSuccess(ApiResultData<String> apiResult) {
        if (apiResult.getStatus() != 2000) {
            ToastDialogUtils.getInstance().showInfoMessage(context, apiResult.getMessage());
            return;
        }
        photo = apiResult.getData();
        photo = (StringUtil.isLocalPhoto(photo) ? "" : OKHttpUtil.IMG_URL) + photo;
    }

    @Override
    public void onUploadFileFails(Exception e) {
        ToastDialogUtils.getInstance().showInfoMessage(context, R.string.network_error);
        photo = null;
        rlPhoto.setVisibility(View.GONE);
        ivAddPhoto.setVisibility(View.VISIBLE);
    }

    @Override
    public void onScanPaperSuccess(ApiResultData<String> apiResultData) {
        ToastDialogUtils.getInstance().showInfoMessage(context, apiResultData.getMessage());
        if (apiResultData.getStatus() != 2000) {
            return;
        }
        LogUtil.getInstance().insertOrReplaceData("掃描送貨單" + mBean.getDocketNo() + apiResultData.getMessage());
        refreshView();
        String docketNo = DocketUtil.getInstance().getDocketNo();
        if (TextUtils.isEmpty(docketNo)) {
            return;
        }
        if (docketNo.equals(mBean.getDocketNo())) {
            EventBus.getDefault().post(new Event(EventCode.EVENT_TRUCK));
        }
    }

    @Override
    public void onScanPaperFails(Exception e) {
        ToastDialogUtils.getInstance().showInfoMessage(context, R.string.network_error);
    }

    @Override
    public void showLoading() {
        LoadingDialogUtils.getInstance().showLoading(context);
    }

    @Override
    public void hideLoading() {
        LoadingDialogUtils.getInstance().dismiss();
    }

    class MyOnClickListener implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            int id = v.getId();
            if (id == R.id.btn_confirm) {
                String docketNo = etDocket.getText().toString();
                if (TextUtils.isEmpty(docketNo)) {
                    ToastDialogUtils.getInstance().showInfoMessage(context, R.string.p_input_scan_docket);
                    return;
                }
                LogUtil.getInstance().insertOrReplaceData("掃描送貨單" + docketNo);
                Intent intent = new Intent(context, DocketActivity.class);
                intent.putExtra(AllConstants.DOCKET, docketNo);
                startActivity(intent);
            } else if (id == R.id.iv_scan) {
                if (PermissionUtil.addPermission(getActivity(),
                        new String[]{Manifest.permission.CAMERA, Manifest.permission.VIBRATE},
                        AllConstants.PIC_SCAN)) {
                    toCapture();
                }
            } else if (id == R.id.iv_add_photo) {
                CommDialogUtils.showComboPicDialog(getActivity(), "");
            } else if (id == R.id.iv_delete) {
                photo = "";
                rlPhoto.setVisibility(View.GONE);
                ivAddPhoto.setVisibility(View.VISIBLE);
            } else if (id == R.id.iv_photo) {
                Intent intent1 = new Intent();
                intent1.setClass(context, ImagePreviewActivity.class);
                ArrayList<String> listPhotos = new ArrayList<>();
                listPhotos.add((StringUtil.isLocalPhoto(photo) ? "" : OKHttpUtil.IMG_URL) + photo);
                intent1.putExtra(AllConstants.WHAT, listPhotos);
                startActivity(intent1);
            } else if (id == R.id.btn_submit) {
                if (DocketUtil.getInstance().getUpgradeLevel() == AllConstants.UPGRADE_FIRST) {
                    ToastUtil.showToast(R.string.upgrade_first);
                    LogUtil.getInstance().insertOrReplaceData(getString(R.string.upgrade_log, AppUtil.getInstance().getVersion()));
                    return;
                }
                if (TextUtils.isEmpty(photo)) {
                    ToastDialogUtils.getInstance().showInfoMessage(context, R.string.p_add_pic);
                    return;
                }
                String docketNo1 = etDocket.getText().toString();
                if (TextUtils.isEmpty(docketNo1)) {
                    ToastDialogUtils.getInstance().showInfoMessage(context, R.string.p_input_scan_docket);
                    return;
                }
                mBean = new ScanPaperDto();
                mBean.setDocketNo(docketNo1);
                mBean.setPhoto(photo);
                mPresenter.scanPaper(mBean);
            }
        }
    }

    private void toCapture() {
//        Intent intent = new Intent(context, CaptureActivity.class);
//        startActivityForResult(intent, AllConstants.PIC_SCAN);
        activityResultLauncher.launch(new Intent(context, CaptureActivity.class));
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (PermissionUtil.requestPermission(grantResults)) {
            switch (requestCode) {
                case ComboPicDialog.PIC_CAMERA:
                    PhotoUtil.getInstance().toCamera(getActivity());
                    break;
                case ComboPicDialog.PIC_GALLERY:
                    PhotoUtil.getInstance().toGallery(getActivity());
                    break;
                case AllConstants.PIC_SCAN:
                    toCapture();
                    break;
            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != 0) {
            if (requestCode == AllConstants.PIC_CAMERA) {
                photo = PhotoUtil.getInstance().handlePhoto(context);
                setPhoto();
            } else if (requestCode == AllConstants.PIC_GALLERY && data != null) {
                if (data.getData() != null) {
                    photo = FileUtils.getFilePathByUri(context, data.getData());
                    setPhoto();
                }
            }
        }
    }

    private void setPhoto() {
        rlPhoto.setVisibility(View.VISIBLE);
        ivAddPhoto.setVisibility(View.GONE);
        ImageUtil.loadImg(context, photo, ivPhoto);
        mPresenter.upload(photo);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            refreshView();
        }
    }

    private void refreshView() {
        etDocket.setText("");
        photo = "";
        rlPhoto.setVisibility(View.GONE);
        ivAddPhoto.setVisibility(View.VISIBLE);
    }
}
